# -*- coding: utf-8 -*-
"""
告警策略配置路由
提供告警策略管理相关的Web接口
"""

from flask import Blueprint, render_template, jsonify, request, redirect, url_for
from common.logger import get_logger

logger = get_logger(__name__)

bp = Blueprint('alarm_strategy', __name__)


@bp.route('/')
def index():
    """告警策略配置主页"""
    return render_template('alarm_strategy_config.html')


@bp.route('/list')
def list_strategies():
    """获取告警策略列表"""
    try:
        # 这里应该从数据库获取告警策略列表
        strategies = [
            {
                'id': 1,
                'name': '错误日志告警',
                'description': '监控ERROR级别的日志并发送告警',
                'enabled': True,
                'conditions': {
                    'level': ['ERROR'],
                    'keywords': ['exception', 'error']
                },
                'actions': [
                    {
                        'type': 'wechat',
                        'config': {'webhook_url': 'https://example.com/webhook'}
                    },
                    {
                        'type': 'email',
                        'config': {'to_emails': ['admin@example.com']}
                    }
                ],
                'created_at': '2024-01-01 10:00:00'
            },
            {
                'id': 2,
                'name': '性能告警',
                'description': '监控性能相关的日志',
                'enabled': True,
                'conditions': {
                    'keywords': ['timeout', 'slow', 'performance']
                },
                'actions': [
                    {
                        'type': 'wechat',
                        'config': {'webhook_url': 'https://example.com/webhook'}
                    }
                ],
                'created_at': '2024-01-01 10:00:00'
            }
        ]
        return jsonify({'success': True, 'data': strategies})
    except Exception as e:
        logger.error(f"获取告警策略列表失败: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@bp.route('/create', methods=['GET', 'POST'])
def create_strategy():
    """创建告警策略"""
    if request.method == 'GET':
        return render_template('alarm_strategy_create.html')
    
    try:
        data = request.get_json()
        name = data.get('name')
        description = data.get('description')
        enabled = data.get('enabled', True)
        conditions = data.get('conditions', {})
        actions = data.get('actions', [])
        
        # 这里应该保存到数据库
        logger.info(f"创建告警策略: {name}")
        
        return jsonify({'success': True, 'message': '告警策略创建成功'})
    except Exception as e:
        logger.error(f"创建告警策略失败: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@bp.route('/<int:strategy_id>')
def get_strategy(strategy_id):
    """获取告警策略详情"""
    try:
        # 这里应该从数据库获取告警策略详情
        strategy = {
            'id': strategy_id,
            'name': '示例策略',
            'description': '这是一个示例告警策略',
            'enabled': True,
            'conditions': {
                'level': ['ERROR'],
                'keywords': ['error']
            },
            'actions': [
                {
                    'type': 'wechat',
                    'config': {'webhook_url': 'https://example.com/webhook'}
                }
            ],
            'created_at': '2024-01-01 10:00:00'
        }
        return jsonify({'success': True, 'data': strategy})
    except Exception as e:
        logger.error(f"获取告警策略详情失败: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@bp.route('/<int:strategy_id>/edit', methods=['GET', 'POST'])
def edit_strategy(strategy_id):
    """编辑告警策略"""
    if request.method == 'GET':
        return render_template('alarm_strategy_edit.html', strategy_id=strategy_id)
    
    try:
        data = request.get_json()
        name = data.get('name')
        description = data.get('description')
        enabled = data.get('enabled', True)
        conditions = data.get('conditions', {})
        actions = data.get('actions', [])
        
        # 这里应该更新数据库
        logger.info(f"更新告警策略 {strategy_id}: {name}")
        
        return jsonify({'success': True, 'message': '告警策略更新成功'})
    except Exception as e:
        logger.error(f"更新告警策略失败: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@bp.route('/<int:strategy_id>/delete', methods=['DELETE'])
def delete_strategy(strategy_id):
    """删除告警策略"""
    try:
        # 这里应该从数据库删除
        logger.info(f"删除告警策略: {strategy_id}")
        
        return jsonify({'success': True, 'message': '告警策略删除成功'})
    except Exception as e:
        logger.error(f"删除告警策略失败: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@bp.route('/<int:strategy_id>/toggle', methods=['POST'])
def toggle_strategy(strategy_id):
    """启用/禁用告警策略"""
    try:
        data = request.get_json()
        enabled = data.get('enabled')
        
        # 这里应该更新数据库
        logger.info(f"切换告警策略状态 {strategy_id}: {enabled}")
        
        return jsonify({'success': True, 'message': '告警策略状态更新成功'})
    except Exception as e:
        logger.error(f"切换告警策略状态失败: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@bp.route('/<int:strategy_id>/test', methods=['POST'])
def test_strategy(strategy_id):
    """测试告警策略"""
    try:
        data = request.get_json()
        test_log = data.get('test_log')
        
        # 这里应该测试策略匹配
        logger.info(f"测试告警策略 {strategy_id}")
        
        # 模拟测试结果
        test_result = {
            'strategy_id': strategy_id,
            'matched': True,
            'reason': '日志级别匹配ERROR条件',
            'timestamp': '2024-01-01 10:00:00'
        }
        
        return jsonify({'success': True, 'data': test_result})
    except Exception as e:
        logger.error(f"测试告警策略失败: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@bp.route('/<int:strategy_id>/alarms')
def get_strategy_alarms(strategy_id):
    """获取策略触发的告警记录"""
    try:
        # 这里应该从数据库获取告警记录
        alarms = [
            {
                'id': 1,
                'log_message': '数据库连接失败',
                'triggered_at': '2024-01-01 10:00:00',
                'status': 'sent'
            },
            {
                'id': 2,
                'log_message': '服务启动异常',
                'triggered_at': '2024-01-01 09:00:00',
                'status': 'sent'
            }
        ]
        return jsonify({'success': True, 'data': alarms})
    except Exception as e:
        logger.error(f"获取策略告警记录失败: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@bp.route('/<int:strategy_id>/stats')
def get_strategy_stats(strategy_id):
    """获取策略统计信息"""
    try:
        # 这里应该从数据库获取统计信息
        stats = {
            'total_triggers': 50,
            'success_rate': 0.95,
            'last_triggered': '2024-01-01 10:00:00',
            'avg_response_time': 1.5
        }
        return jsonify({'success': True, 'data': stats})
    except Exception as e:
        logger.error(f"获取策略统计信息失败: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@bp.route('/action-types')
def get_action_types():
    """获取支持的动作类型"""
    try:
        action_types = [
            {'id': 'wechat', 'name': '企业微信', 'description': '发送企业微信消息'},
            {'id': 'email', 'name': '邮件', 'description': '发送邮件通知'},
            {'id': 'webhook', 'name': 'Webhook', 'description': '调用Webhook接口'}
        ]
        return jsonify({'success': True, 'data': action_types})
    except Exception as e:
        logger.error(f"获取动作类型失败: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500 